package com.getpebble.android.framework.install.app;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat.BigTextStyle;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Pair;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.model.AppVersion;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.common.model.FrameworkState.EventType;
import com.getpebble.android.common.model.FrameworkState.StateListener;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.common.provider.model.PblInstalledJoinLockerAppDataModel;
import com.getpebble.android.framework.comm.MessageRouter;
import com.getpebble.android.framework.endpoint.EndpointRequest;
import com.getpebble.android.framework.endpoint.EndpointRequest.EndpointAction;
import com.getpebble.android.framework.endpoint.EndpointRequest.EndpointArgumentKeys;
import com.getpebble.android.framework.endpoint.InstallAppEndpoint.AppInstallResult;
import com.getpebble.android.framework.protocol.EndpointId;
import com.getpebble.android.main.activity.MainActivity;
import com.getpebble.android.util.HttpUtils;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.ArrayList;

public class AppUpdateManager {
    public static final String TAG = AppUpdateManager.class.getSimpleName();
    private static AppUpdateManager sInstance;
    private int mAppUpdateNotificationNumber = 1;
    private ArrayList<Pair<Uri, String>> mAppsToUpdate = new ArrayList();
    private final FrameworkState mFrameworkState;
    private int mIndex = 0;
    private boolean mIsUpdating = false;
    private ArrayList<String> mUpdatedApps = new ArrayList();

    static /* synthetic */ class AnonymousClass2 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult = new int[AppInstallResult.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[AppInstallResult.SUCCESS.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[AppInstallResult.ERROR_NO_CONNECTED_DEVICE.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[AppInstallResult.ERROR_PRF.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[AppInstallResult.ERROR_TIMEOUT.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
        }
    }

    public static synchronized AppUpdateManager create(FrameworkState frameworkState) {
        AppUpdateManager appUpdateManager;
        synchronized (AppUpdateManager.class) {
            sInstance = new AppUpdateManager(frameworkState);
            appUpdateManager = sInstance;
        }
        return appUpdateManager;
    }

    public static synchronized AppUpdateManager getInstance() {
        AppUpdateManager appUpdateManager;
        synchronized (AppUpdateManager.class) {
            appUpdateManager = sInstance;
        }
        return appUpdateManager;
    }

    public void cleanup() {
        Trace.debug(TAG, "Cleaning up");
        this.mUpdatedApps.clear();
        this.mAppsToUpdate.clear();
        this.mIndex = 0;
        this.mIsUpdating = false;
    }

    private AppUpdateManager(FrameworkState frameworkState) {
        if (frameworkState == null) {
            throw new IllegalArgumentException("Framework State Cannot Be Null");
        }
        this.mFrameworkState = frameworkState;
    }

    public void checkForUpdates(ContentResolver contentResolver, PblDevice device) {
        if (this.mIsUpdating) {
            Trace.debug(TAG, "Is already updating -- ignoring request to process upgrades.");
            return;
        }
        PblPreferences preferences = new PblPreferences(PebbleApplication.getAppContext());
        if (!preferences.getBooleanData(PrefKey.AUTO_APP_UPDATES_ENABLED, true)) {
            Trace.debug(TAG, "Not processing any updates: auto app updates are disabled.");
        } else if (!HttpUtils.hasInternetConnection(PebbleApplication.getAppContext()) || (preferences.getBooleanData(PrefKey.AUTO_APP_UPDATES_WIFI_ONLY, true) && !HttpUtils.isWifiConnected(PebbleApplication.getAppContext()))) {
            Trace.debug(TAG, "Not processing any updates: not connected to a valid network.");
        } else if (device == null) {
            Trace.error(TAG, "Failed to process updates: device was null");
        } else {
            Trace.debug(TAG, "Processing Updates! Connected Device = " + device);
            Cursor cursor = PblInstalledJoinLockerAppDataModel.fetchAppsCursor(contentResolver, device);
            if (cursor == null) {
                Trace.warning(TAG, "checkForUpdates: cursor is null");
                return;
            }
            this.mIsUpdating = true;
            while (cursor.moveToNext()) {
                String appName = cursor.getString(cursor.getColumnIndex("app_name"));
                AppVersion lockerVersion = new AppVersion(cursor.getString(cursor.getColumnIndex("locker_version")));
                AppVersion installedVersion = new AppVersion(cursor.getString(cursor.getColumnIndex("installed_version")));
                Trace.debug(TAG, appName + ": Installed version: " + installedVersion.getVersionTag() + " | Locker version: " + lockerVersion.getVersionTag());
                if (installedVersion.compareTo(lockerVersion) < 0) {
                    Trace.debug(TAG, "Adding " + appName + " to list of apps to update");
                    this.mAppsToUpdate.add(new Pair(Uri.parse(cursor.getString(cursor.getColumnIndex("pbw_file"))), appName));
                } else {
                    try {
                        Trace.debug(TAG, appName + " is already up to date, not updating.");
                    } catch (Exception e) {
                        Trace.error(TAG, "Failed to process upgrades", e);
                        this.mIsUpdating = false;
                    } finally {
                        cursor.close();
                    }
                }
            }
            Trace.debug(TAG, "Finished processing apps for upgrade");
            if (!this.mIsUpdating || this.mAppsToUpdate == null || this.mAppsToUpdate.isEmpty()) {
                Trace.debug(TAG, "No apps are out of date, not installing any updates.");
                cleanup();
                return;
            }
            Trace.debug(TAG, "Requesting update of " + this.mAppsToUpdate.size() + " apps.");
            processUpdates(device);
        }
    }

    private void processUpdates(final PblDevice device) {
        if (this.mIndex == this.mAppsToUpdate.size()) {
            Trace.info(TAG, "Finished updating apps");
            showUpdateNotification(PebbleApplication.getAppContext(), this.mUpdatedApps.size(), buildNotificationMessage());
            cleanup();
            return;
        }
        Uri uri = ((Pair) this.mAppsToUpdate.get(this.mIndex)).first;
        final String appName = ((Pair) this.mAppsToUpdate.get(this.mIndex)).second;
        Trace.debug(TAG, "Updating " + appName + "...");
        Bundle args = new Bundle();
        args.putParcelable(EndpointArgumentKeys.URI.toString(), uri);
        args.putBoolean(EndpointArgumentKeys.AUTO_START_APP.toString(), false);
        args.putBoolean(EndpointArgumentKeys.ALLOW_REINSTALL.toString(), true);
        args.putBoolean(EndpointArgumentKeys.VIBRATE.toString(), false);
        EndpointRequest endpointRequest = new EndpointRequest(EndpointId.APP_INSTALL_MANAGER, EndpointAction.ADD_APP, args);
        MessageRouter messageRouter = MessageRouter.getRouter(device);
        if (messageRouter == null) {
            Trace.error(TAG, "Not sending update message to watch: message router was null.");
            cleanup();
            return;
        }
        final FrameworkState appUpdateFrameworkState = new FrameworkState(this.mFrameworkState);
        appUpdateFrameworkState.setStateListener(new StateListener() {
            public void onStateChanged() {
                EventType lastEvent = appUpdateFrameworkState.getLastEvent();
                if (lastEvent == null) {
                    Trace.debug(AppUpdateManager.TAG, "Last event was null");
                } else if (lastEvent.equals(EventType.APP_INSTALL_COMPLETE)) {
                    AppInstallResult appInstallResult = AppInstallResult.fromValue(appUpdateFrameworkState.getAppInstallResult());
                    switch (AnonymousClass2.$SwitchMap$com$getpebble$android$framework$endpoint$InstallAppEndpoint$AppInstallResult[appInstallResult.ordinal()]) {
                        case SMTPMessage.RETURN_FULL /*1*/:
                            Trace.debug(AppUpdateManager.TAG, "Successfully Updated " + appName);
                            AppUpdateManager.this.mUpdatedApps.add(appName);
                            break;
                        case SMTPMessage.RETURN_HDRS /*2*/:
                            Trace.error(AppUpdateManager.TAG, "No device connected, aborting updates.");
                            AppUpdateManager.this.cleanup();
                            return;
                        case ListInfo.INDETERMINATE /*3*/:
                            AppUpdateManager.this.cleanup();
                            Trace.error(AppUpdateManager.TAG, "Device is in PRF Mode, aborting updates.");
                            return;
                        case SMTPMessage.NOTIFY_DELAY /*4*/:
                            AppUpdateManager.this.cleanup();
                            Trace.error(AppUpdateManager.TAG, "Install timedout, aborting updates.");
                            return;
                        default:
                            Trace.error(AppUpdateManager.TAG, "Failed to update " + appName + ". Status: " + appInstallResult.name());
                            break;
                    }
                    AppUpdateManager.this.mIndex = AppUpdateManager.this.mIndex + 1;
                    AppUpdateManager.this.processUpdates(device);
                }
            }
        });
        messageRouter.onRequest(endpointRequest, appUpdateFrameworkState);
    }

    private void showUpdateNotification(Context context, int numItemsUpdated, String updatedAppList) {
        if (context == null) {
            Trace.error(TAG, "Failed to show app update notifications: context was null");
        } else if (numItemsUpdated == 0) {
            Trace.debug(TAG, "Not showing notification: no apps were successfully updated");
        } else if (new PblPreferences(context).getBooleanData(PrefKey.AUTO_APP_UPDATES_NOTIFICATIONS, true)) {
            String title = context.getString(R.string.app_update_installed_title, new Object[]{Integer.valueOf(numItemsUpdated)});
            String message = context.getString(R.string.app_update_installed_message, new Object[]{updatedAppList});
            NotificationManager notificationManager = (NotificationManager) context.getSystemService("notification");
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
            Builder builder = new Builder(context);
            builder.setContentTitle(title);
            builder.setContentText(message);
            builder.setContentIntent(contentIntent);
            builder.setSmallIcon(R.drawable.connected_status_bar);
            builder.setStyle(new BigTextStyle().bigText(message));
            builder.setWhen(System.currentTimeMillis());
            notificationManager.notify(this.mAppUpdateNotificationNumber, builder.build());
            this.mAppUpdateNotificationNumber++;
        } else {
            Trace.error(TAG, "Not showing update notification: preference is disabled.");
        }
    }

    private String buildNotificationMessage() {
        StringBuilder updatedAppsBuilder = new StringBuilder();
        int i = 0;
        while (i < this.mUpdatedApps.size()) {
            updatedAppsBuilder.append((String) this.mUpdatedApps.get(i));
            if (this.mAppsToUpdate.size() > 1 && i == this.mUpdatedApps.size() - 2) {
                updatedAppsBuilder.append(" & ");
            } else if (i != this.mUpdatedApps.size() - 1) {
                updatedAppsBuilder.append(", ");
            }
            i++;
        }
        if (updatedAppsBuilder == null) {
            return "";
        }
        return updatedAppsBuilder.toString();
    }
}
